#ifndef LOG_CLIENT_H
#define LOG_CLIENT_H

#include <iostream>
#include <cstring>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <unistd.h>  // 添加此行以包含close()函数声明
#include <sstream>

#include <string>
#include <cstdint>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "../common/config.h"

class LogClient {
public:
    // 添加日志等级枚举
    enum class LogLevel {
        FATAL,
        ERROR,
        WARN,
        INFO,
        DEBUG,
        TRACE
    };    

    // 初始化日志客户端
    bool init(const std::string& software_name, const std::string& service_name, const std::string& server_ip = "broadcast", const std::string& config_file = "config.json");
    
    // 基础日志发送函数
    void sendLog(LogLevel level, const std::string& content);
    
    // 等级特定的便捷日志函数
    void logTrace(const std::string& content);
    void logDebug(const std::string& content);
    void logInfo(const std::string& content);
    void logWarn(const std::string& content);
    void logError(const std::string& content);
    void logFatal(const std::string& content);
    
    // 释放资源
    void release();
    
    // 单例模式
    static LogClient& getInstance() {
        static LogClient instance;
        return instance;
    }
    
    LogClient(const LogClient&) = delete;
    LogClient& operator=(const LogClient&) = delete;
    
private:
    LogClient() : is_initialized_(false), is_running_(false) {}
    ~LogClient() { release(); }
    
    // 工作线程函数，处理日志发送
    void workerThread();
    std::string logLevelToString(LogLevel level);
    // 构建日志格式
    std::string buildLogString(LogLevel level, const std::string& content);
    
    int socket_fd_;
    struct sockaddr_in server_addr_;
    std::string server_ip_;
    uint16_t server_port_;
    std::string software_name_;
    std::string service_name_;
    std::string mac_address_;
    
    std::thread worker_thread_;
    std::queue<std::string> log_queue_;
    std::mutex queue_mutex_;
    std::condition_variable queue_cond_;
    std::atomic<bool> is_initialized_;
    std::atomic<bool> is_running_;
};

#endif // LOG_CLIENT_H